#!/usr/bin/env python3
"""Why the call agent did what it did on a call: one timeline of what it heard, what it thought, what it ran and
what it decided, turn by turn.

  sidekick-debug [--call <id or prefix>] [--transcript <session.jsonl>]… [--agent-only] [--full]

Defaults to the call agent's current (or last) call. Reads:

  calls/<call>/agent.json   each agent session that heard the call: model, effort, transcript, and the rules it
                            worked under (Standing constraints, Settings › Agent) when it joined (sidekick-listen)
  the session transcript    ~/.claude/projects/…/<session>.jsonl: every feed line delivered, each turn's thinking
                            summary, tool calls and results, and its one-line decision (`pass: …`, `noted: …`)
  calls/<call>/notebook.jsonl   the notes and the operator's reactions, for the totals

A call from before calls/<call>/agent.json existed falls back to $SIDEKICK_HOME/agent.json when it names the call, then
to any transcript under ~/.claude/projects that mentions it.

--agent-only hides the speech lines and keeps the agent's turns; --full prints thinking, results and speech untruncated.
"""
import argparse
import json
import re
import shlex
import sys
from collections import Counter
from datetime import datetime
from pathlib import Path

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import sidekick_context as ctx  # noqa: E402

EVENT = re.compile(r"<event>(.*?)</event>", re.S)
STAMP = re.compile(r"^\[(\d{4}-\d\d-\d\dT[^\]]*)\]\s*(.*)$", re.S)


def local(stamp):
    try:
        return datetime.fromisoformat(stamp.replace("Z", "+00:00")).astimezone().strftime("%H:%M:%S")
    except ValueError:
        return ""


def clip(text, n, full):
    text = " ".join(str(text).split())
    return text if full or len(text) <= n else text[: n - 1] + "…"


def find_call(arg):
    calls = ctx.SIDEKICK / "calls"
    if not arg:
        arg = ctx.agent_record().get("call")
        if not arg:
            folders = sorted((p for p in calls.glob("*") if p.is_dir()), key=lambda p: p.stat().st_mtime)
            arg = folders[-1].name if folders else None
    if not arg:
        sys.exit("sidekick-debug: no call (pass --call)")
    matches = [p.name for p in calls.glob(f"{arg}*") if p.is_dir()]
    if len(matches) > 1:
        sys.exit(f"sidekick-debug: {arg} matches {len(matches)} calls: {', '.join(m[:8] for m in matches)}")
    return matches[0] if matches else arg


def sessions_for(call, given):
    if given:
        return [({}, Path(t)) for t in given]
    recorded = ctx.read_json(ctx.SIDEKICK / "calls" / call / "agent.json").get("sessions") or []
    if recorded:
        return [(s, Path(s["transcript"])) for s in recorded if s.get("transcript")]
    rec = ctx.agent_record()
    if rec.get("call") == call and rec.get("transcript"):
        return [(rec, Path(rec["transcript"]))]
    folder = ctx.SIDEKICK / "calls" / call
    since = folder.stat().st_mtime - 2 * 86400 if folder.exists() else 0
    needle = f"call={call}".encode()
    found = []
    for p in (Path.home() / ".claude" / "projects").glob("*/*.jsonl"):
        try:
            if p.stat().st_mtime >= since and needle in p.read_bytes():
                found.append(p)
        except OSError:
            continue
    return [({}, p) for p in sorted(found, key=lambda p: p.stat().st_mtime)]


def tool_summary(block):
    name, inp = block.get("name", "?"), block.get("input") or {}
    if name == "Bash":
        command = inp.get("command", "")
        command = re.sub(r"^\s*export SIDEKICK_HOME=\S+;\s*", "", command)
        try:
            words = shlex.split(command)
        except ValueError:
            words = []
        for i, w in enumerate(words):
            if w.endswith("/sidekick") and "note" in words[i + 1:]:
                rest = words[words.index("note", i) + 1:]
                title = next((r for r in rest if not r.startswith("-") and not re.fullmatch(r"[0-9a-f-]{36}", r)), "")
                verb = "revise note" if "--id" in rest else "note"
                return f"{verb}: {title!r}"
        command = re.sub(r"^SIDEKICK_HOME=\S+\s+", "", command)
        command = re.sub(r"'[^']*/(?:bin|scripts)/([^'/]+)'", r"\1", command)
        command = re.sub(r"\S*/(?:bin|scripts)/(sidekick[\w-]*)", r"\1", command)
        return "$ " + command
    if name == "ToolSearch":
        return f"ToolSearch {inp.get('query', '')}"
    return f"{name.removeprefix('mcp__')} {json.dumps(inp, ensure_ascii=False)}"


def result_text(block):
    c = block.get("content")
    if isinstance(c, list):
        c = " ".join(b.get("text", "") for b in c if isinstance(b, dict))
    return str(c or "")


def timeline(path, call, a, totals):
    out = []
    in_call = re.search(rf"\[sidekick\] call env=\S+ call={re.escape(call)}", Path(path).read_text(errors="replace")) is None
    turn = []
    heard_since = 0

    def flush(duration=None):
        nonlocal turn, heard_since
        if turn:
            if duration is not None:
                turn[-1] += f"   [{duration:.1f}s]"
            out.extend(turn)
        turn = []
        heard_since = 0

    for raw in open(path, errors="replace"):
        try:
            d = json.loads(raw)
        except ValueError:
            continue
        kind = d.get("type")
        msg = d.get("message") or {}
        content = msg.get("content")
        if kind == "user" and isinstance(content, str) and "<task-notification>" in content:
            for ev in EVENT.findall(content):
                for line in ev.splitlines():
                    if f"call={call}" in line and "[sidekick] call env=" in line:
                        in_call = True
                    if not in_call:
                        continue
                    m = STAMP.match(line)
                    if line.startswith("[sidekick]"):
                        flush()
                        out.append(f"          {line}")
                        if "reaction:" in line:
                            totals["reactions"] += 1
                    elif m:
                        totals["heard"] += 1
                        heard_since += 1
                        if not a.agent_only:
                            flush()
                            out.append(f"{local(m.group(1))}  {clip(m.group(2), 200, a.full)}")
                    if f"call over call={call}" in line:
                        in_call = False
                        totals["over"] = True
            continue
        if not in_call and not totals["over"]:
            continue
        if kind == "assistant" and isinstance(content, list):
            when = local(d.get("timestamp", ""))
            for b in content:
                t = b.get("type")
                if t == "thinking":
                    totals["thinking"] += 1
                    text = b.get("thinking", "")
                    if text.strip():
                        totals["thinking_saved"] += 1
                    turn.append(f"  {when}  ┆ think: {clip(text, 600, a.full)}" if text.strip() else f"  {when}  ┆ (thought; not saved)")
                elif t == "text" and b.get("text", "").strip():
                    text = b["text"].strip()
                    totals["replies"] += 1
                    first = text.split()[0].rstrip(":").lower()
                    totals["decisions"][first if first in ("pass", "considering", "noted", "skipped", "listening.") else "other"] += 1
                    turn.append(f"  {when}  ▸ {clip(text, 400, a.full)}")
                elif t == "tool_use":
                    totals["tools"] += 1
                    s = tool_summary(b)
                    if s.startswith(("note:", "revise note:")):
                        totals["notes"] += 1
                    turn.append(f"  {when}  ⚙ {clip(s, 240, a.full)}")
        elif kind == "user" and isinstance(content, list):
            for b in content:
                if b.get("type") == "tool_result":
                    mark = "✗" if b.get("is_error") else "↳"
                    turn.append(f"            {mark} {clip(result_text(b), 200, a.full)}")
        elif kind == "system" and d.get("subtype") == "turn_duration":
            totals["turns"] += 1
            flush(d.get("durationMs", 0) / 1000)
            totals["over"] = False
    flush()
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--call")
    ap.add_argument("--transcript", action="append")
    ap.add_argument("--agent-only", action="store_true")
    ap.add_argument("--full", action="store_true")
    ap.add_argument("--env", choices=ctx.CLIS, help=argparse.SUPPRESS)
    a = ap.parse_args()
    call = find_call(a.call)
    sessions = sessions_for(call, a.transcript)
    title = next((e.get("title") for e in map(json.loads, filter(str.strip, (ctx.read(ctx.SIDEKICK / "calls" / call / "notebook.jsonl") or "").splitlines()))
                  if e.get("type") == "call"), "")
    print(f"call {call}  {title}")
    if not sessions:
        print("no agent transcript found for this call")
        return 1
    for rec, path in sessions:
        totals = Counter()
        totals["decisions"] = Counter()
        print(f"\n=== session {rec.get('id') or path.stem[:8]}  model={rec.get('model', '?')} effort={rec.get('effort', '?')}")
        print(f"    transcript {path}")
        if rec.get("constraints"):
            print("    standing constraints when it joined:")
            for line in rec["constraints"].splitlines():
                print(f"      {clip(line, 220, a.full)}")
        if rec.get("instructions"):
            print(f"    Settings › Agent: {clip(rec['instructions'], 300, a.full)}")
        if not path.exists():
            print("    (transcript is gone)")
            continue
        print()
        for line in timeline(path, call, a, totals):
            print(line)
        d = totals["decisions"]
        print(f"\n    {totals['heard']} lines heard · {totals['turns']} turns · {totals['notes']} notes written · {totals['tools']} tool calls · "
              f"{totals['reactions']} reactions")
        print(f"    decisions: " + ", ".join(f"{k} {v}" for k, v in d.most_common()))
        print(f"    thinking: {totals['thinking']} turns thought, {totals['thinking_saved']} with a saved summary")
    return 0


if __name__ == "__main__":
    sys.exit(main())
